package com.sbtr.util;

import com.sbtr.common.LoginConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;

public class HttpServletRequestUtil {

	// 获取客户端ip地址
	public static String getClientIp(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("http_client_ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		// 如果是多级代理，那么取第一个ip为客户ip
		if (ip != null && ip.indexOf(",") != -1) {
			ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
		}
		return ip;
	}
	
	/**
	 * 从请求参数或者请求头里获取用户token
	 * @param request
	 * @return
	 */
	public static String getreqParam(HttpServletRequest request, String tokenName){
		if(StringUtils.isNotEmpty(tokenName)){
			String token = request.getParameter(tokenName);
			if( StringUtils.isBlank(token) )
				token = request.getHeader(tokenName);
			return token;
		}
		return null;
	}

	/**
	 * 获取request
	 * @return
	 */
	public static HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}

	/**
	 * 获取当前请求用户
	 * @return
	 */
	public static String getLoginUserName(){
		HttpServletRequest request = getRequest();
		String username = request.getParameter(LoginConstants.REQUEST_PARAM_USERNAME);
		return username;
	}

	/**
	 * SpringMvc下获取session
	 * @return
	 */
	public static HttpSession getSession() {
		HttpSession session = getRequest().getSession();
		return session;
	}

	/**
	 * 获取真实路径，根据传入路径，若传入路径，不存在进行创建并返回，若传入是文件，判断文件存在则返回，不存在，则创建文件所在目录，并返回null
	 * @param url
	 * @return
	 */
	public static String getRealPath(String url){

		String resourceUrl = "static/";
		// 必须存在该目录
		String realPath = ClassUtils.getDefaultClassLoader().getResource(resourceUrl).getPath();
		try {
			realPath = URLDecoder.decode(realPath, "UTF-8"); // 存在中文处理
		} catch (UnsupportedEncodingException e1) {
			System.out.println("中文目录问题！！");
		}

		if(url.startsWith("/")){
			realPath += url.substring(1);
			resourceUrl += url.substring(1);
		}else{
			realPath += url;
			resourceUrl += url;
		}

		String flag = FileHelper.getSuffix(realPath); // 判断是否存在后缀
		File file = new File(realPath);
		if (!file.exists() && StringHelper.isNotEmpty(flag)) { // 是文件，并且文件不存在
			realPath = FileHelper.getDirsUrl(realPath);
			File fileDirs = new File(realPath); // 提取文件所属上级目录，判断是否存在
			if (!fileDirs.exists()) {
				fileDirs.mkdirs(); // 创建不存在的目录
			}
			return null;
		}

		if (!file.exists()) {
			file.mkdirs(); // 创建不存在的目录
			realPath = ClassUtils.getDefaultClassLoader().getResource(resourceUrl).getPath();
		}

		URI uri = null;
		try {
			uri = new URI(realPath);
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		realPath = uri.getPath().toString();  // 转换中文编码
		return realPath;
	}

}
